package com.sikadwafastdaisfondturbo.pretloan.ui.credit.page

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.sikadwafastdaisfondturbo.lib_baseadapter.SikadwaOnItemChildClickListener
import com.sikadwafastdaisfondturbo.pretloan.R
import com.sikadwafastdaisfondturbo.pretloan.adapter.CreditAccountAdapter
import com.sikadwafastdaisfondturbo.pretloan.adapter.RecommendAppAdapter
import com.sikadwafastdaisfondturbo.pretloan.databinding.PageCreditCommonBinding
import com.sikadwafastdaisfondturbo.pretloan.pro.ProFragment
import com.sikadwafastdaisfondturbo.pretloan.status.StatusRepository
import com.sikadwafastdaisfondturbo.pretloan.utils.BarUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.DensityUtils
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardAddDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardOnlyOneWarningDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.dialog.BindCardOtherDialog
import com.sikadwafastdaisfondturbo.pretloan.utils.event.EventType
import com.sikadwafastdaisfondturbo.pretloan.utils.helper.StarDialogHelper
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls
import com.sikadwafastdaisfondturbo.pretloan.utils.http.AppUrls.addCommonParams
import com.sikadwafastdaisfondturbo.pretloan.utils.http.IHttpCallback
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：通用状态列表，包含：审核中、拒绝、放贷中、放贷中法语
 */
class CreditCommonPage(): ProFragment() {
    lateinit var binding: PageCreditCommonBinding
    private var mCreditInfo: JSONObject? = null

    //账户列表
    private var mAccountAdapter: CreditAccountAdapter? = null
    //推荐APP列表
    private var mAppAdapter: RecommendAppAdapter? = null

    constructor(obj: JSONObject): this(){
        this.mCreditInfo = obj
    }

    override fun getRootView(inflater: LayoutInflater): View {
        binding = PageCreditCommonBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        binding.parentLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        binding.contentLayout.visibility = View.INVISIBLE

        initRefreshLayout()
        initRvAccount()
        initRvApp()
    }

    override fun initListener() {
        binding.imgKefu.setOnClickListener {
            showKefuDialog(mCreditInfo!!.optString("eventRemark"))
            addEvent(EventType.CLICK.CLICK_CUSTOMER,mCreditInfo!!.optString("eventRemark"))
        }
        binding.imgUser.setOnClickListener {
            showPersonalDialog(mCreditInfo!!.optString("eventRemark"))
            addEvent(EventType.CLICK.CLICK_USER,mCreditInfo!!.optString("eventRemark"))
        }
        //添加绑卡
        binding.addLayout.setOnClickListener {
            showBindCardDialog()
        }
    }

    override fun initData() {
        showLoading()
        loadCreditInfoAction()
        loadAccountListAction()
        loadRecommendAppAction()
    }

    /**
     * 状态改变，需要刷新页面
     */
    fun refreshView(data: JSONObject){
        this.mCreditInfo = data
        loadCreditInfoAction()
        loadAccountListAction()
        loadRecommendAppAction()
    }

    /* 初始化刷新 */
    private fun initRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 初始化账户列表
     */
    private fun initRvAccount() {
        binding.rvAccount.setHasFixedSize(true)
        binding.rvAccount.isNestedScrollingEnabled = false
        binding.rvAccount.isFocusableInTouchMode = false //不需要焦点
        binding.rvAccount.layoutManager = LinearLayoutManager(context)
//        val topDecoration = DensityUtils.dp2px(16f)
//        binding.rvApp.addItemDecoration(LinearDecoration(0,0,topDecoration,0))
        mAccountAdapter = CreditAccountAdapter(binding.rvAccount)
        binding.rvAccount.adapter = mAccountAdapter!!
        binding.rvAccount.itemAnimator = DefaultItemAnimator()
        mAccountAdapter!!.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            val item = mAccountAdapter!!.getItem(position)
        })
    }

    /**
     * 初始化可安装App列表
     */
    private fun initRvApp() {
        binding.emptyLayout.emptyLayout.visibility = View.GONE
        binding.rvApp.setHasFixedSize(true)
        binding.rvApp.isNestedScrollingEnabled = false
        binding.rvApp.isFocusableInTouchMode = false //不需要焦点
        binding.rvApp.layoutManager = LinearLayoutManager(context)
        val topDecoration = DensityUtils.dp2px(12f)
//        binding.rvApp.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        mAppAdapter = RecommendAppAdapter(binding.rvApp)
        binding.rvApp.adapter = mAppAdapter!!
        binding.rvApp.itemAnimator = DefaultItemAnimator()
        mAppAdapter!!.setOnItemChildClickListener(SikadwaOnItemChildClickListener { _, childView, position ->
            val item = mAppAdapter!!.getItem(position)
            if (childView.id == R.id.installLayout) {//点击安装
                addEvent(EventType.CLICK.CLICK_CREDIT_APPLY_FAILED_RECOMMEND_APP_INSTALL,item.optString("appName"))
                val appLink = item.optString("appLink")
                if (appLink.isNotEmpty()){
                    val uri = Uri.parse(item.optString("appLink"))
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }
            }
        })
    }

    /**
     * 审核中
     */
    private fun showAuditView(){
        binding.vStatusBg.setBackgroundResource(R.drawable.credit_apply_audit_bg)
        binding.textSyatus.text = requireContext().getString(R.string.credit_common_status_audit)
        binding.textSyatus.setBackgroundResource(R.drawable.radius_fill_ff0059aa_10)
        binding.imgStatusIcon.setImageResource(R.mipmap.img_credit_apply_audit_icon)

        binding.tipsLayout1.visibility = View.VISIBLE
        binding.conseilsLayout.visibility = View.GONE
        binding.accountLayout.visibility = View.VISIBLE
        binding.textRecommendMsg.text = requireContext().getString(R.string.credit_common_status_recommended_audit_msg)

        //只有法语地区才需要添加账户按钮
        if (!Configs.isFrench()){
            binding.addLayout.visibility = View.GONE
        }
        loadStarCommentAction()
    }

    /**
     * 已拒绝
     */
    private fun showFailedView(){
        binding.vStatusBg.setBackgroundResource(R.drawable.credit_apply_failed_bg)
        binding.textSyatus.text = requireContext().getString(R.string.credit_common_status_rejected)
        binding.textSyatus.setBackgroundResource(R.drawable.radius_fill_fff07b66_10)
        binding.imgStatusIcon.setImageResource(R.mipmap.img_credit_apply_failed_icon)

        binding.tipsLayout1.visibility = View.GONE
        binding.conseilsLayout.visibility = View.GONE
        binding.accountLayout.visibility = View.GONE
        binding.textRecommendMsg.text = requireContext().getString(R.string.credit_common_status_recommended_failed_msg)
    }

    /**
     * 放贷中
     */
    private fun showLendingView(){
        binding.vStatusBg.setBackgroundResource(R.drawable.credit_apply_lending_bg)
        binding.textSyatus.text = requireContext().getString(R.string.credit_common_status_lending)
        binding.textSyatus.setBackgroundResource(R.drawable.radius_fill_ff43da84_10)
        binding.imgStatusIcon.setImageResource(R.mipmap.img_credit_apply_lending_icon)

        binding.tipsLayout1.visibility = View.VISIBLE
        binding.conseilsLayout.visibility = View.VISIBLE
        binding.accountLayout.visibility = View.VISIBLE
        binding.textRecommendMsg.text = requireContext().getString(R.string.credit_common_status_recommended_audit_msg)
        //只有法语地区才需要添加账户按钮
        if (!Configs.isFrench()){
            binding.conseilsLayout.visibility = View.GONE
            binding.addLayout.visibility = View.GONE
        }
        loadStarCommentAction()
    }

    /**
     * 只有一个账户提示添加绑卡
     */
    private fun showOnlyOneAccountAddDialog(){
        val dialog = BindCardOnlyOneWarningDialog(requireContext(),object : BindCardOnlyOneWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnAddMore){
                    showBindCardDialog()
                }
            }
        })
        dialog.show()
    }

    /**
     * 添加绑卡dialog
     */
    private fun showBindCardDialog(){
        addEvent(EventType.CLICK.CLICK_USER_ACCOUNT_ADD,"CreditAuditFrench Page")
        val bindCardDialog = BindCardAddDialog(context,"CreditAuditFrench Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                onAddBindCardAction(phoneNumber,typeObj.optString("value"),"NO")
            }
        })
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    fun showBingAccountOtherDialog(otherInfo: JSONObject?) {
        if (otherInfo != null){
            val replaceDialog = BindCardOtherDialog(context,"CreditAuditFrench Page",object : BindCardOtherDialog.IDialogCallback{
                override fun onClick(view: View?) {
                    if (view!!.id == R.id.btnConfirm){//添加
                        onAddBindCardAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                    }
                }
            })
            replaceDialog.show()
            replaceDialog.setBindAccountInfo(otherInfo)
        }
    }

    /**
     * 设置贷款信息
     */
    @SuppressLint("SetTextI18n")
    private fun setCreditDataInfo(obj: JSONObject){
        binding.contentLayout.visibility = View.VISIBLE
        binding.textAmount.text = obj.optString("amount") + " " + obj.optString("currency")
        binding.textDays.text = String.format(requireContext().getString(R.string.credit_apply_loan_term_days),obj.optString("days"))

        //1、判断是否存在 订单状态
        if (mCreditInfo!!.has("orderStatus")) {
            val orderStatus = mCreditInfo!!.optString("orderStatus")
            //待还款
//            if (StatusRepository(null, orderStatus).isRepayNow()) {
//                showRepayPage()
//                return
//            }
            //放款中
            if (StatusRepository(null, orderStatus).isDisbursing()) {
                showLendingView()
                return
            }
            //申请贷款被拒绝
            if (StatusRepository(null, orderStatus).isRejected()) {
                showFailedView()
                return
            }
        }

        //2、判断是否存在 贷款申请状态
        if (mCreditInfo!!.has("applyStatus")){
            val applyStatus = mCreditInfo!!.optString("applyStatus")
            //审核中
            if (StatusRepository(applyStatus).isReviewing()){
                showAuditView()
                return
            }
            //被拒绝
            if (StatusRepository(applyStatus).isRejected()){
                showFailedView()
                return
            }
        }
    }

    /**
     * 设置绑定的账户列表
     */
    private fun setAccountList(accountList: ArrayList<JSONObject>){
        mAccountAdapter!!.data = accountList

        /**
         * 法语审核中 && 只有一个账户  提示新增绑卡
         */
        if (Configs.isFrench()){
            //申请状态
            val applyStatus = mCreditInfo!!.optString("applyStatus")
            //审核中 && 只有一个账户
            if (StatusRepository(applyStatus).isReviewing() && accountList.size <= 1){
                showOnlyOneAccountAddDialog()
            }
        }
    }

    /**
     * 设置推荐APP列表
     */
    private fun setRecommendAppList(appList: ArrayList<JSONObject>){
        if (appList.size == 0){
            binding.rvApp.visibility = View.GONE
            binding.emptyLayout.emptyLayout.visibility = View.VISIBLE
            return
        }
        binding.rvApp.visibility = View.VISIBLE
        binding.emptyLayout.emptyLayout.visibility = View.GONE
        mAppAdapter!!.data = appList
    }

    /**
     * 获取贷款信息
     */
    private fun loadCreditInfoAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_APPLY)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null){
                    setCreditDataInfo(obj)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                binding.refreshLayout.finishRefresh()
            }
        })
    }

    /**
     * 获取账户已绑定的列表
     */
    private fun loadAccountListAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_LIST)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val array = data.optJSONArray("obj")
                if (array != null && array.length() > 0) {
                    val accountList = arrayListOf<JSONObject>()
                    for (i in 0..<array.length()){
                        accountList.add(array.optJSONObject(i))
                    }
                    setAccountList(accountList)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                binding.refreshLayout.finishRefresh()
            }
        })
    }

    /**
     * 获取推荐APP列表
     */
    private fun loadRecommendAppAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.RECOMMEND_APP_LIST)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                val appList = arrayListOf<JSONObject>()
                if (obj != null && obj.has("dcProductList")) {
                    val appArray = obj.optJSONArray("dcProductList")
                    if (appArray != null && appArray.length() > 0) {
                        for (i in 0..<appArray.length()) {
                            appList.add(appArray.optJSONObject(i))
                        }
                    }
                    setRecommendAppList(appList)
                }
            }

            override fun onRequestError(error: JSONObject) {
                setRecommendAppList(arrayListOf())
            }

            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取评分配置
     */
    private fun loadStarCommentAction() {
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.STAR_COMMENT)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                StarDialogHelper.showStarDialog(requireContext(),obj,true)
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 添加绑定账户（法语）
     */
    fun onAddBindCardAction(mobile: String,walletChannel: String, bindFlag:String) {
        showLoading()
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.ACCOUNT_ADD)
            put("walletMobile",mobile)
            put("walletMobileConfirm",mobile)
            put("walletChannel",walletChannel)
            put("addBindFlag",bindFlag)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj") ?: JSONObject()
                //刷新列表
                loadAccountListAction()

                // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                val addBindFlag = obj.optString("addBindFlag")
                if (addBindFlag == "YES") {
                    //需要提示绑定另一个渠道账户
                    var otherAccountInfo: JSONObject? = null

                    //用于从APP配置中获取（walletChannels）对应的信息
                    val channel = obj.optString("channel")
                    val commonData = JSONObject(Configs.getSPString(Configs.SPKEY.SIKADWA_COMMON))
                    val customize = commonData.optJSONObject("customize")
                    if (customize != null) {
                        val walletChannels = customize.optJSONArray("walletChannels")
                        if (walletChannels != null && walletChannels.length() > 0) {
                            for (i in 0..<walletChannels.length()) {
                                val item = walletChannels.optJSONObject(i)
                                if (channel == item.optString("value")) {
                                    otherAccountInfo = item
                                    break
                                }
                            }
                        }

                        // 只有非空的情况下才处理
                        if (otherAccountInfo != null) {
                            otherAccountInfo.put("walletMobile", mobile)
                            //提示绑定另一个渠道账户
                            showBingAccountOtherDialog(otherAccountInfo)
                            return
                        }
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEvent(EventType.PAGE.PAGE_CREDIT_COMMON_START,mCreditInfo!!.optString("eventRemark"))
    }

    override fun onDestroy() {
        super.onDestroy()
        addEvent(EventType.PAGE.PAGE_CREDIT_COMMON__END,mCreditInfo!!.optString("eventRemark"))

    }
}